package com.xez.data
{
	import com.xez.fs.FsExtension;
	import com.xez.util.FsConst;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	public class ImgRoot extends CacheData
	{
		public function ImgRoot()
		{
		}
		
		[Bindable]
		public var bytedata:ByteArray;
		
		[Bindable]
		public var name:String;
		public var webname:String;
		public var dirname:String;
		public var url:String;
		private var loaded:Boolean = false;
		
		private var dataLoader:URLLoader;
		
		override public function get cachename():String
		{
			return webname + '_' + dirname + '_' + name;
		}
		
		public function load():void
		{
			if (loaded)
				return;
			
			trace('开始加载图片', name, url);
			msg = '正在加载图片';
			
			if (hasCache())
			{
				trace('从缓存中读取');
				bytedata = getCache();
				loaded = true;
				msg = null;
			}
			else
			{
				trace('从URL读取');
				dataLoader = new URLLoader();
				dataLoader.dataFormat = URLLoaderDataFormat.BINARY;
				dataLoader.addEventListener(Event.COMPLETE, dataLoader_completeHandler);
				dataLoader.addEventListener(IOErrorEvent.IO_ERROR, dataLoader_errorHandler);
				dataLoader.addEventListener(ProgressEvent.PROGRESS, dataLoader_progressHandler);
				dataLoader.load(new URLRequest(url));
			}
		}
		
		private function dataLoader_completeHandler(e:Event):void
		{
			trace('图片' + name + '加载成功');
			msg = null;
			loaded = true;
			bytedata = dataLoader.data;
			saveCache(bytedata);
		}
		
		private function dataLoader_progressHandler(e:ProgressEvent):void
		{
			msg = '正在加载图片' + Math.ceil( (e.bytesLoaded / e.bytesTotal ) * 100) + '%';
		}
		
		private function dataLoader_errorHandler(e:IOErrorEvent):void
		{
			if (hasCache())
			{
				trace('从缓存中读取');
				bytedata = getCache();
				loaded = true;
				msg = null;
			}
			else
			{
				msg = '图片加载失败';
				trace('图片' + name + '加载失败');
			}
		}
		
		/*保存图片到本地*/
		public function save():void
		{
			trace('保存图片:', webname, dirname, name);
			try
			{
				var saveFile:File = new File().resolvePath(FsConst.downloadFile.nativePath + '/' + 
					webname + '/' + dirname + '/' + name);
				var fs:FileStream = new FileStream();
				fs.open(saveFile, FileMode.WRITE);
				fs.writeBytes(bytedata, 0, bytedata.bytesAvailable);
				fs.close();
				trace('保存图片成功');
				new FsExtension().tipShort('保存成功' +  saveFile.nativePath);
			} 
			catch(error:Error)
			{
				trace('保存图片失败:',error.message);
				new FsExtension().tipShort('保存失败');
			}
		}
		
	}
}